import React, { Suspense } from "react";
import { formatMessage } from 'umi-plugin-react/locale';
import PageLoading from "@/components/PageLoading";
import PageHeaderWrapper from "@/components/PageHeaderWrapper";
import { Avatar, Button, Card, Icon, List, message, Modal } from "antd";
import styles from "./index.less";
import { connect } from "dva";
import RobotAdd from "@/pages/robotManagement/robotAdd";
import { routerRedux } from "dva/router";
import tableDataCheck from "@/utils/isBackPrevPage";

const { confirm } = Modal;

class RobotList extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			loading: false,
			list: [],
			addVisible: false,
		};
	}

	componentDidMount() {
		this.getRobotList();
	}

	getRobotList = () => {
		const { dispatch } = this.props;
		this.setState({ loading: true }, () => {
			dispatch({
				type: "robots/fetchRobotList",
				payload: {},
				callback: (res) => {
					this.setState({
						list: res,
						loading: false,
					});
				},
			});
		});
	};

	handleDelete = (item) => {
		const that = this;
		confirm({
			title: formatMessage({ id: 'robotManagement.robotList.deleteConfirm' }),
			okText: formatMessage({ id: 'robotManagement.robotList.confirm' }),
			okType: "danger",
			cancelText: formatMessage({ id: 'robotManagement.robotList.cancel' }),
			onOk() {
				const { dispatch } = that.props;
				const { list, current } = that.state;
				dispatch({
					type: "robots/fetchRobotRemove",
					payload: { id: item.id },
					callback: (res) => {
						message.info(res.message);
						//判断是否需要加载上一页数据 2022.4.8
						const newCurrent = tableDataCheck(list, current);
						that.setState({ current: newCurrent }, () => {
							that.getRobotList();
						});
					},
				});
			},
			onCancel() { },
		});
	};

	openAdd = () => {
		this.RobotAdd.initModal()
	};

	handleEdit = (item) => {
		const { history } = this.props;
		let moduleList = [];
		if (item.moduleRobot) {
			moduleList.push('robot')
		}
		if (item.moduleKefu) {
			moduleList.push("kefu")
		}
		if (item.moduleTicket) {
			moduleList.push("ticket")
		}
		history.push({
			pathname: "/enterprise/robotManagement/robotEdit/" + item.id,
			query: { platform: item.applicationPlatform, applicationId: item.id, moduleList: moduleList.toString(), isllmCustom: item.type, loginType: item.loginType },
		});
	};

	renderCardHead = (item) => {
		let name = '';
		let icon = "";
		let img = "";
		switch (item.applicationPlatform) {
			case 'QWX_NATIVE':
				name = formatMessage({ id: 'robotManagement.robotList.qwxNative' });
				img = '/qw.png'
				break;
			case 'QWX_CORP_BUILD':
				name = formatMessage({ id: 'robotManagement.robotList.qwxCorpBuild' });
				img = '/qw.png'
				break;
			case 'DD_NATIVE':
				name = formatMessage({ id: 'robotManagement.robotList.ddNative' });
				icon = 'dingding'
				break;
			case 'DD_CORP_BUILD':
				name = formatMessage({ id: 'robotManagement.robotList.ddCorpBuild' });
				icon = 'dingding'
				break;
			case 'FS_CORP_BUILD':
				name = formatMessage({ id: 'robotManagement.robotList.fsCorpBuild' });
				img = '/feishuWhite.svg'
				break;
			case 'FS_NATIVE':
				name = formatMessage({ id: 'robotManagement.robotList.fsNative' });
				img = '/feishuWhite.svg'
				break;
			case 'PURE_WEB':
				name = formatMessage({ id: 'robotManagement.robotList.pureWeb' });
				icon = 'credit-card'
				break;
			case 'DIGITAL_SCREEN':
				name = formatMessage({ id: 'robotManagement.robotList.digitalScreen' });
				icon = 'fund'
				break;
			default:
				name = '网页版';
				icon = 'credit-card'
				break;
		}

		if (item.type === 1) {
			name = formatMessage({ id: 'robotManagement.robotList.llmConsultation' });
		}

		return (
			<div style={{ textAlign: "center", position: "relative", padding: " 20px 0", }}>
				<div style={{ display: "flex", alignItems: "center" }}>
					{
						icon ? <Avatar className={styles.cardAvatar} icon={icon}></Avatar>
							: <Avatar className={styles.cardAvatar} src={staticPath + img}></Avatar>
					}

					<div style={{ fontWeight: "bold", fontSize: "16px", width: 'calc(100% - 80px)', textAlign: 'left' }}>{item.name}</div>
				</div>
			</div>
		);
	};

	render() {
		const { loading, current, total, list, addVisible } = this.state;
		return (
			<Suspense fallback={<PageLoading />}>
				<PageHeaderWrapper>
					<Card bordered={false} style={{height:"100%"}}>
            <div className={styles.robotBox}>
              <div style={{ marginBottom:24 }}>
                <Button type={"primary"} onClick={this.openAdd}>{formatMessage({ id: 'robotManagement.robotList.add' })}</Button>
              </div>
              <List
                rowKey='id'
                loading={loading}
                grid={{ gutter: 10, lg: 4, md: 3, sm: 2, xs: 1 }}
                dataSource={list}
                renderItem={(item) => (
                  <List.Item>
                    <Card
                      className={styles.card}
                      actions={item.applicationPlatform == 'SYS_WEB' ? [
                        <a onClick={() => this.handleEdit(item)}>{formatMessage({ id: 'robotManagement.robotList.edit' })}</a>
                      ] : [
                        <a onClick={() => this.handleDelete(item)}>{formatMessage({ id: 'robotManagement.robotList.delete' })}</a>,
                        <a onClick={() => this.handleEdit(item)}>{formatMessage({ id: 'robotManagement.robotList.edit' })}</a>,
                      ]}
                      bodyStyle={{ padding: "0px" }}
                    >
                      <Card.Meta title={this.renderCardHead(item)} style={{ margin: "-1px 0" }} />
                    </Card>
                  </List.Item>
                )}
              />

              <RobotAdd
                refreshList={this.getRobotList}
                onRef={(ref) => (this.RobotAdd = ref)}
              />
            </div>
          </Card>
				</PageHeaderWrapper>
			</Suspense>
		);
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(RobotList);
